package com.elpebe.sysabk.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

import com.elpebe.sysabk.model.PersistentObject;
import com.elpebe.sysabk.repository.IOperations;

@Transactional
public abstract class AbstractService<T extends PersistentObject> implements IOperations<T> {

    // read - one
    @Override
    @Transactional(readOnly = true)
    public T findOne(final long id) {
        return getDao().findOne(id);
    }

    // read - all
    @Override
    @Transactional(readOnly = true)
    public List<T> findAll() {
//        return Lists.newArrayList(getDao().findAll());
    	List<T> list = new ArrayList<T>();
    	Iterable<T> it = getDao().findAll();
    	
    	if(it != null){
    		Iterator<T> iter = it.iterator();
    		while(iter.hasNext()){
    			T t = iter.next();
    			list.add(t);
    		}
    	}
    	return list;
    }

    @Override
    public Page<T> findPaginated(final int page, final int size) {
        return getDao().findAll(new PageRequest(page, size));
    }

    // write
    @Override
    public T create(final T entity) {
        return getDao().save(entity);
    }

    @Override
    public T update(final T entity) {
//    	T updated = findOne(entity.getId());
        return getDao().save(entity);
    }

    @Override
    public void delete(final Long id) {
        getDao().delete(id);
    }

    @Override
    public void deleteById(final long entityId) {
        getDao().delete(entityId);
    }

    protected abstract PagingAndSortingRepository<T, Long> getDao();

}
